package com.xjrsoft.module.erpModel.caseErpMaterial.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.yulichang.toolkit.MPJWrappers;
import com.xjrsoft.common.annotation.XjrLog;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.enums.YesOrNoEnum;
import com.xjrsoft.common.model.result.R;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.common.utils.VoToColumnUtil;
import com.xjrsoft.module.erpModel.caseErpMaterial.dto.*;
import com.xjrsoft.module.erpModel.caseErpMaterial.entity.CaseErpMaterialClasses;
import com.xjrsoft.module.erpModel.caseErpMaterial.entity.CaseErpMaterialProperty;
import com.xjrsoft.module.erpModel.caseErpMaterial.service.ICaseErpMaterialPropertyService;
import com.xjrsoft.module.erpModel.caseErpMaterial.vo.CaseErpMaterialPropertyExportVo;
import com.xjrsoft.module.erpModel.caseErpMaterial.vo.CaseErpMaterialPropertyVo;
import com.xjrsoft.module.erpModel.caseErpUnit.entity.CaseErpUnit;
import com.xjrsoft.module.organization.entity.User;
import com.xjrsoft.module.workflow.utils.WorkFlowUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 物料属性配置【case_erp_material_property】 前端控制器
 * </p>
 *
 * @author hnyyzy
 * @since 2023-06-19
 */
@RestController
@RequestMapping(GlobalConstant.CASE_ERP_MATERIAL +"/caseErpMaterialProperty")
@Api(value = GlobalConstant.CASE_ERP_MATERIAL +"/caseErpMaterialProperty", tags = "物料属性配置")
@AllArgsConstructor
public class CaseErpMaterialPropertyController {
    private ICaseErpMaterialPropertyService caseErpMaterialPropertyService;

    @GetMapping(value = "/list")
    @ApiOperation("物料属性列表")
    public R list() {
        List<CaseErpMaterialProperty> list = caseErpMaterialPropertyService.list(Wrappers.<CaseErpMaterialProperty>query().lambda().eq(CaseErpMaterialProperty::getState, YesOrNoEnum.YES.getCode()));
        return R.ok(list);
    }

    @GetMapping(value = "/page")
    @ApiOperation("物料属性配置列表分页")
    public R page(CaseErpMaterialPropertyPageDto dto) {
        if (ObjectUtil.isNotNull(dto.getStartTime()) && ObjectUtil.isNotNull(dto.getEndTime())) {
            dto.setStartTime(WorkFlowUtil.getStartOfDay(dto.getStartTime()));
            dto.setEndTime(WorkFlowUtil.getEndOfDay(dto.getEndTime()));
        }
        IPage<CaseErpMaterialPropertyVo> page = caseErpMaterialPropertyService.selectJoinListPage(ConventPage.getPage(dto), CaseErpMaterialPropertyVo.class,
                MPJWrappers.<CaseErpMaterialProperty>lambdaJoin()
                        .distinct()
                        .orderByDesc(CaseErpMaterialProperty::getCreateDate)
                        .like(StrUtil.isNotBlank(dto.getPropertyName()), CaseErpMaterialProperty::getPropertyName, dto.getPropertyName())
                        .between(ObjectUtil.isNotNull(dto.getStartTime()) && ObjectUtil.isNotNull(dto.getEndTime())
                                , CaseErpMaterialProperty::getCreateDate, dto.getStartTime(), dto.getEndTime())
                        .selectAs(User::getName, CaseErpMaterialPropertyVo::getCreateUserName)
                        .select(CaseErpMaterialProperty::getId)
                        .select(CaseErpMaterialProperty.class, x -> VoToColumnUtil.fieldsToColumns(CaseErpMaterialPropertyVo.class).contains(x.getProperty()))
                        .leftJoin(User.class, User::getId, CaseErpMaterialProperty::getCreateUserId));

        PageOutput<CaseErpMaterialPropertyVo> pageOutput = ConventPage.getPageOutput(page);
        return R.ok(pageOutput);
    }


    @GetMapping(value = "/info")
    @ApiOperation(value = "根据id查询物料属性配置信息")
    public R info(@RequestParam Long id) {
        CaseErpMaterialProperty caseErpMaterialProperty = caseErpMaterialPropertyService.getById(id);
        if (caseErpMaterialProperty == null) {
            R.error("找不到此物料属性配置！");
        }
        return R.ok(BeanUtil.toBean(caseErpMaterialProperty, CaseErpMaterialPropertyVo.class));
    }

    @PostMapping
    @ApiOperation(value = "新增物料属性配置")
    public R add(@Valid @RequestBody AddCaseErpMaterialPropertyDto dto) {
        long count = caseErpMaterialPropertyService.count(Wrappers.<CaseErpMaterialProperty>query().lambda().eq(CaseErpMaterialProperty::getPropertyName, dto.getPropertyName()));
        if (count > 0) {
            return R.error("此物料属性已经存在！");
        }
        CaseErpMaterialProperty  caseErpMaterialProperty= BeanUtil.toBean(dto, CaseErpMaterialProperty.class);
        caseErpMaterialPropertyService.save(caseErpMaterialProperty);
        return R.ok(true);
    }

    @PutMapping
    @ApiOperation(value = "修改物料属性配置")
    public R update(@Valid @RequestBody UpdateCaseErpMaterialPropertyDto dto) {
        CaseErpMaterialProperty caseErpMaterialProperty = BeanUtil.toBean(dto, CaseErpMaterialProperty.class);
        caseErpMaterialPropertyService.updateById(caseErpMaterialProperty);
        return R.ok(true);
    }

    @DeleteMapping
    @ApiOperation(value = "删除")
    @XjrLog(value = "删除物料属性配置")
    public R delete(@Valid @RequestBody Long id) {
        return R.ok(caseErpMaterialPropertyService.removeById(id));
    }

    @PostMapping(value = "/export")
    @ApiOperation(value = "导出")
    @XjrLog(value = "导出表单数据")
    public ResponseEntity<byte[]> export(@Valid @RequestBody List<Long> ids) {
        List<CaseErpMaterialPropertyExportVo> caseErpMaterialPropertyExportVoList = caseErpMaterialPropertyService.selectJoinList(CaseErpMaterialPropertyExportVo.class,
                MPJWrappers.<CaseErpMaterialProperty>lambdaJoin()
                        .distinct()
                        .in(CaseErpMaterialProperty::getId, ids)
                        .selectAs(User::getName, CaseErpMaterialPropertyExportVo::getCreateUserName)
                        .select(CaseErpMaterialProperty::getId)
                        .select(CaseErpMaterialProperty.class, x -> VoToColumnUtil.fieldsToColumns(CaseErpMaterialPropertyExportVo.class).contains(x.getProperty()))
                        .leftJoin(User.class, User::getId, CaseErpMaterialProperty::getCreateUserId));
        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        EasyExcel.write(bot, CaseErpMaterialPropertyExportVo.class).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(caseErpMaterialPropertyExportVoList);
        return R.fileStream(bot.toByteArray(), "物料属性配置" + ExcelTypeEnum.XLSX.getValue());
    }

    @PostMapping("/import")
    @ApiOperation(value = "导入")
    public R importData(@RequestParam MultipartFile file) throws IOException {
        List<AddCaseErpMaterialPropertyDto> savedDataList = EasyExcel.read(file.getInputStream()).head(AddCaseErpMaterialPropertyDto.class).sheet().doReadSync();
        caseErpMaterialPropertyService.saveBatch(BeanUtil.copyToList(savedDataList, CaseErpMaterialProperty.class));
        return R.ok(true);
    }

    @GetMapping("/export")
    @ApiOperation(value = "下载模板")
    @SneakyThrows
    public ResponseEntity<byte[]> export() {
        List<AddCaseErpMaterialPropertyDto> caseErpMaterialPropertyDtoList = new ArrayList<>();
        ByteArrayOutputStream bot = new ByteArrayOutputStream();
        EasyExcel.write(bot, AddCaseErpMaterialPropertyDto.class).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(BeanUtil.copyToList(caseErpMaterialPropertyDtoList, AddCaseErpMaterialPropertyDto.class));
        return R.fileStream(bot.toByteArray(), "物料属性配置模板" + ExcelTypeEnum.XLSX.getValue());
    }

}
